/**
 * 创建一个 WebSocket 客户端实例
 * @param {string} url - WebSocket 地址
 * @returns {Object} - 返回一个客户端对象
 */
function createWebsocketClient(url) {
  const client = {};
  let ws = null;
  let reconnectFlag = false;
  let pingTimer = null;

  client.reconnectInterval = 1000 * 30; //重连间隔
  client.pingInterval = 1000 * 40; //心跳间隔

  //事件回调
  client.onOpen = () => {};
  client.onError = () => {};
  client.onClose = () => {};
  client.onMessage = () => {};

  //设置 URL
  client.setUrl = function (newUrl) {
    url = newUrl;
  };

  //连接
  client.connect = function () {
    if (!url) {
      throw new Error("还未设置websocket服务端的url");
    }

    if (
      ws &&
      (ws.readyState === WebSocket.CONNECTING ||
        ws.readyState === WebSocket.OPEN)
    ) {
      console.log("WebSocket 正在连接或已连接，无需重复连接");
      return;
    }

    //清空旧事件，方式重复绑定事件
    if (ws) {
      ws.close();
      ws = null;
    }

    try {
      if (window.WebSocket) {
        ws = new WebSocket(url);
      } else {
        throw new Error("浏览器不支持websocket，推荐使用新版chrome浏览器");
      }
    } catch (e) {
      console.error("创建 WebSocket 失败", e);
      return;
    }

    ws.onopen = (event) => {
      console.log("websocket：onopen 连接成功");
      startPing();
      client.onOpen(event);
    };
    ws.addEventListener("error", (event) => {
      console.log("websocket：onerror 遇到错误", event);
      reconnect();
      client.onError(event);
    });
    ws.onclose = (event) => {
      console.log("websocket：onclose 连接关闭");
      reconnect();
      client.onClose(event);
    };
    ws.addEventListener("message", (event) => {
      console.log("websocket：onmessage 收到消息", event);
      client.onMessage(event);
    });
  };

  //重连机制
  function reconnect() {
    if (reconnectFlag) {
      return;
    }
    reconnectFlag = true;
    stopPing();
    setTimeout(() => {
      console.log("websocket：断线重连");
      client.connect();
      reconnectFlag = false;
    }, client.reconnectInterval);
  }

  //发送心跳
  function startPing() {
    stopPing();
    pingTimer = setInterval(() => {
      if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send('{"type":"ping"}');
      }
    }, client.pingInterval);
  }

  //停止心跳
  function stopPing() {
    if (pingTimer) {
      clearInterval(pingTimer);
      pingTimer = null;
    }
  }

  //发送消息
  client.send = function (data) {
    if (ws && ws.readyState === WebSocket.OPEN) {
      return ws.send(data);
    } else {
      console.warn("WebSocket not connected. Message not sent.");
      throw new Error("WebSocket not connected. Message not sent.");
    }
  };

  //主动关闭连接
  client.close = function () {
    if (ws) {
      ws.close();
    }
    stopPing();
  };

  return client;
}

export default createWebsocketClient;
